package com.cjyd.hrjb.controller;

import com.cjyd.hrjb.exception.ServiceException;
import com.cjyd.hrjb.model.dto.ResponseDto;
import com.cjyd.hrjb.utils.ResponseUtil;
import com.cjyd.hrjb.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.List;
import java.util.Locale;
import java.util.Optional;

/**
 * Created fei wo by 2020/4/5
 */
@Slf4j
@RestControllerAdvice
public class ExceptionController extends ResponseEntityExceptionHandler {

    @Autowired
    private MessageSource messageSource;

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        if (body == null) {
            if (HttpStatus.BAD_REQUEST.equals(status)) {
                status = HttpStatus.OK;
                body = ResponseUtil.error(ResultCode.PARAMS_INVALID.setMsg(ex.getMessage()));
            }else if (status.is4xxClientError()) {
                body  = ResponseUtil.error(ResultCode.CLIENT_ERROR.setMsg(ex.getMessage()));
            }else {
                body = ResponseUtil.error(ResultCode.SYSTEM_ERROR);
            }
        }
        return super.handleExceptionInternal(ex, body, headers, status, request);
    }

    @ExceptionHandler(ServiceException.class)
    public ResponseDto<Void> handleServiceException(ServiceException ex) {
        return ResponseUtil.error(ex.getResultCode());
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        ResponseDto<Void> body = ResponseUtil.error(ResultCode.PARAMS_INVALID.setMsg(getMessageByErrors(ex.getBindingResult())));
        status = HttpStatus.OK;
        return handleExceptionInternal(ex, body, headers, status, request);
    }

    private String getMessageByErrors(BindingResult bindingResult) {
        return bindingResult.hasErrors() ? messageSource.getMessage(bindingResult.getAllErrors().get(0), Locale.getDefault()) : "参数不合法";
    }
}
